package main.java;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LeetCode811 {
    public static List<String> subdomainVisits(String[] cpdomains) {
        Map<String, Integer> map = new HashMap<>();
        List<String> resultList = new ArrayList<>();
        for (int i=0; i<cpdomains.length; i++) {
            String domain = cpdomains[i];
            String[] domainnull = domain.split(" ");
            String[] domaindao = domainnull[1].split("\\.");
            Integer num = map.getOrDefault(domainnull[1], 0);
            map.put(domainnull[1], Integer.valueOf(domainnull[0]) + num);
            if (num == null || num.intValue() == 0) {
                resultList.add(domainnull[1]);
            }
            for (int j = domaindao.length - 1; j >= 1; j--) {
                if (j == domaindao.length - 1) {
                    Integer numJ = map.getOrDefault(domaindao[j], 0);
                    map.put(domaindao[j], Integer.valueOf(domainnull[0]) + numJ);
                    if (numJ == null || numJ.intValue() == 0) {
                        resultList.add(domaindao[j]);
                    }
                }
                if (j  == domaindao.length - 2) {
                    Integer numJ = map.getOrDefault(domaindao[j] + "." + domaindao[j + 1], 0);
                    map.put(domaindao[j] + "." + domaindao[j + 1], Integer.valueOf(domainnull[0]) + numJ);
                    if (numJ == null || numJ.intValue() == 0) {
                        resultList.add(domaindao[j] + "." + domaindao[j + 1]);
                    }
                }
            }
        }
        for (int i = 0; i < resultList.size(); i++) {
            Integer val = map.get(resultList.get(i));
            resultList.set(i, val + " " + resultList.get(i));
        }
        return resultList;
    }

    public static void main(String[] args) {
        String[] cpdomains = {"9001 discuss.leetcode.com"};
        subdomainVisits(cpdomains);
    }
}
